package com.archstoday.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.archstoday.BaseApp;
import com.archstoday.R;
import com.archstoday.activity.LoginActivity;
import com.archstoday.activity.NewDetailsActivity;
import com.archstoday.activity.SchemeDetailActivity;
import com.archstoday.activity.TenderDetailsActivity;
import com.archstoday.adapter.LikeListAdapter;
import com.archstoday.common.AsRes;
import com.archstoday.common.SpfUtils;
import com.archstoday.entity.LikeListEntity;
import com.archstoday.entity.SchemeDetailEntity;
import com.archstoday.utils.OAuthUtils;
import com.archstoday.utils.ToolUtils;
import com.archstoday.view.PullToRefreshLayout;
import com.base.http.common.BaseHttpClient;
import com.base.utils.MySharedPreferencesMgr;
import com.base.utils.StringUtil;
import com.xw.repo.refresh.PullListView;

/**
 * 收藏列表
 */
public class LikeListFragment extends AsBaseFragment implements PullToRefreshLayout.OnRefreshListener {

    private TextView mTitleTv;
    private PullToRefreshLayout mPullLayout;
    private PullListView mPullList;
    private ProgressBar mProgress;
    private LinearLayout mNoneLayout, mLoginNoneLayout;

    private LikeListAdapter mAdapter;

    private int page;
    private View mFootView;
    private boolean isLoadMore;

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_like_list, null);
        mTitleTv = (TextView) view.findViewById(R.id.title_tv);
        mPullLayout = (PullToRefreshLayout) view.findViewById(R.id.pull_layout);
        mPullList = (PullListView) view.findViewById(R.id.pull_list);
        mProgress = (ProgressBar) view.findViewById(R.id.progress_bar);
        mPullLayout.setOnRefreshListener(this);
        mNoneLayout = (LinearLayout) view.findViewById(R.id.search_none_layout);
        mLoginNoneLayout = (LinearLayout) view.findViewById(R.id.login_none_layout);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!StringUtil.isEmpty(MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""))) {
            mPullList.setPullDownEnable(true);
            mPullList.setPullUpEnable(true);
            mLoginNoneLayout.setVisibility(View.GONE);
            page = 1;
            mProgress.setVisibility(View.VISIBLE);
            upData();

        } else {
            mProgress.setVisibility(View.GONE);
            mPullList.setPullDownEnable(false);
            mPullList.setPullUpEnable(false);
            mLoginNoneLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initData(Bundle bundle) {
        mTitleTv.setText(R.string.like_title);
        mAdapter = new LikeListAdapter(mAct);
        mPullList.setAdapter(mAdapter);
        isLoadMore = false;
        mFootView = LayoutInflater.from(mAct).inflate(R.layout.view_load_more, null);
    }

    @Override
    protected void initListener() {
        setOnClickListener(R.id.login_none_layout);

        mPullList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent;
                switch (mAdapter.getItem(i).getCategoryId1()) {
                    case 1:
                        intent = new Intent(mAct, NewDetailsActivity.class);
                        intent.putExtra("id", mAdapter.getItem(i).getArticleId());
                        intent.putExtra("isNews", true);
                        startActivity(intent);
                        break;
                    case 2:
                        intent = new Intent(mAct, TenderDetailsActivity.class);
                        intent.putExtra("id", String.valueOf(mAdapter.getItem(i).getArticleId()));
                        intent.putExtra("title", mAdapter.getItem(i).getLabel());
                        startActivity(intent);
                        break;
                    case 3:
                        intent = new Intent(mAct, NewDetailsActivity.class);
                        intent.putExtra("id", String.valueOf(mAdapter.getItem(i).getArticleId()));
                        intent.putExtra("title", mAdapter.getItem(i).getLabel());
                        startActivity(intent);
                        break;
                    case 221:
                        intent = new Intent(mAct, SchemeDetailActivity.class);
                        intent.putExtra("id", mAdapter.getItem(i).getArticleId());
                        intent.putExtra("title", mAdapter.getItem(i).getLabel());
                        startActivity(intent);
                        break;
                }
            }
        });
    }

    @Override
    public void treatClickEvent(int id) {
        switch (id) {
            case R.id.login_none_layout:
                Intent intent = new Intent(mAct, LoginActivity.class);
                startActivity(intent);
        }
    }

    private void upData() {
        initParameter();
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("token", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));
        mParams.put("plat", "android");
        mParams.put("ifa", BaseApp.getDeviceID(mAct));
        mParams.put("page", page);
        mParams.put("pageSize", 20);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.LIKE_LIST),
                AsRes.LIKE_LIST, mParams, LikeListEntity.class);
    }

    @Override
    protected void onSuccess(String content, BaseHttpClient client, Object parse) {
        mProgress.setVisibility(View.GONE);
        mPullLayout.refreshFinish(true);
        mPullLayout.loadMoreFinish(true);
        if (client.getUrlIdentifier() == AsRes.LIKE_LIST) {
            LikeListEntity entity = (LikeListEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                if (entity.getData() != null && entity.getData().size() > 0) {
                    if (page == 1) {
                        mAdapter.setData(entity.getData());
                    } else {
                        mAdapter.addData(entity.getData());
                    }
                    page++;
                } else {
                    if (isLoadMore) {
                        mNoneLayout.setVisibility(View.GONE);
                        mPullList.addFooterView(mFootView);
                        mPullList.setPullUpEnable(false);
                    } else {
                        mNoneLayout.setVisibility(View.VISIBLE);
                        mPullList.setPullUpEnable(false);
                    }
                }
            } else if (entity.getStatus() == 10005) {
                MySharedPreferencesMgr.setString(SpfUtils.USER_ID, "");
                MySharedPreferencesMgr.setString(SpfUtils.USER_TOKEN, "");
                OAuthUtils.getInstance().cleanUserInfo();

                showToast("登录信息已过期，请重新登录");
                Intent intent = new Intent(mAct, LoginActivity.class);
                startActivity(intent);
            } else {
                showToast(entity.getMsg());
            }
        }
    }

    @Override
    protected void onError(Throwable error, BaseHttpClient client) {
        new Thread() {
            @Override
            public void run() {
                new Handler(Looper.getMainLooper()).post(runnable);
            }
        }.start();
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mProgress.setVisibility(View.GONE);
            mPullLayout.refreshFinish(true);
            mPullLayout.loadMoreFinish(true);

            if (mAdapter.getCount() == 0) {
                mNoneLayout.setVisibility(View.VISIBLE);
                mPullList.setPullUpEnable(false);
            }

            showToast(R.string.intent_error);
        }
    };

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        mPullList.setPullUpEnable(true);
        mPullList.removeFooterView(mFootView);
        isLoadMore = false;
        page = 1;
        upData();
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        isLoadMore = true;
        upData();
    }
}